import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class IPv6Tester {
	
	public ConnectionStatus ipv6Test(String host) throws IOException, InterruptedException {
		String OS = System.getProperty("os.name");
		
		ConnectionStatus ipv6Status = new ConnectionStatus();
		ipv6Status.currentLightStatus = ConnectionStatus.lights.RED;

		boolean ipv6;
		
		if (OS.startsWith("Windows")) {
			ipv6 = windowsTraceroute6(host);
		} else if (OS.startsWith("Linux") || OS.startsWith("Mac")) {
			ipv6 = unixTraceroute6(host);
		} else {
			System.out.println("Unknown Operating System");
			ipv6 = false;
		}		
		
		ipv6Status.ipv6_status = ipv6;
		
		return ipv6Status;
	}

	private static boolean windowsTraceroute6(String host) throws IOException, InterruptedException {
		boolean ipv6 = false;
		
		String s1 = "tracert -6 -d -h 5 -w 1000 ";
		String cmd = s1 + host;
		System.out.println(cmd);

		Runtime r = Runtime.getRuntime();
		Process p = r.exec(cmd);			
		
		BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
		
		String line;
		
		while ((line = is.readLine()) != null) {
			System.out.println(line);
			String[] words = line.split("\\d+ ms");
			if (words.length >= 2) {
				ipv6 = true;
			}
		}
		
		int exitValue = p.waitFor();
		if (exitValue != 0) {
			System.out.println("Windows: Bad Exit Value");
			return false;
		}
		
		return ipv6;		
	}
	
	private static boolean unixTraceroute6(String host) throws IOException, InterruptedException {
		boolean ipv6 = false;
		
		String s1 = "traceroute6 -q 3 -m 5 -w 1000 ";
		String cmd = s1 + host;
		System.out.println(cmd);

		Runtime r = Runtime.getRuntime();
		Process p = r.exec(cmd);			
		
		BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
		
		String line;
		String linePlus;
		
		while ((line = is.readLine()) != null) {
			System.out.println(line);
			linePlus = line + "end";
			String[] words = linePlus.split("\\d*.\\d+ ms");
			if (words.length >= 2) {
				ipv6 = true;
			}
		}
		
		int exitValue = p.waitFor();
		if (exitValue != 0) {
			System.out.println("Unix: Bad Exit Value");
			return false;
		}
		
		return ipv6;		
	}
}